import 'dart:async';

import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/material.dart' hide Action;
import 'package:flutter_inappbrowser/flutter_inappbrowser.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:www.znpigai.teacher/global_store/state.dart';

import 'action.dart';
import 'state.dart';

Widget buildView(
    HomeworkAnswerListState state, Dispatch dispatch, ViewService viewService) {
  final ListAdapter adapter = viewService.buildAdapter();
  final ScrollController _scrollController = new ScrollController();
  _scrollController.addListener(() {
    // 如果下拉的当前位置到scroll的最下面
    if (_scrollController.position.pixels ==
        _scrollController.position.maxScrollExtent) {
      dispatch(HomeworkDetailActionCreator.onLoad());
    }
  });

  List<Widget> _listView() {
    var widgets = <Widget>[];
    if (adapter.itemCount == 0) {
      if (!state.isLoading) {
        widgets.add(Center(
            child: Column(
          children: <Widget>[
            Image.asset("assets/images/empty_list.png",
                width: 200, height: 200, fit: BoxFit.fill),
            Text('让AI助手为您提升批改效率！', style: TextStyle(color: Colors.grey))
          ],
        )));
      }
    } else {
      widgets.add(ListView.builder(
        physics: AlwaysScrollableScrollPhysics(), // work when several items
        itemBuilder: (context, index) {
          if (index == adapter.itemCount) {
            return Padding(
              padding: const EdgeInsets.all(8.0),
              child: new Center(
                child: new Opacity(
                  opacity: state.isLoading ? 0.0 : 1.0,
                  child: Text(index != 0 ? '没有更多了' : '',
                      style: TextStyle(color: Colors.grey)),
                ),
              ),
            );
          } else {
            return adapter.itemBuilder(context, index);
          }
        },
        itemCount: adapter.itemCount + 1,
        controller: _scrollController,
      ));
    }

    if (state.isLoading) {
      widgets.add(Center(
          child: SizedBox(
              width: 110,
              height: 110,
              child: Card(
                  key: null,
                  color: Colors.black45,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(15.0),
                  ),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      SpinKitFadingCircle(
                        color: Colors.blue,
                        size: 50,
                      ),
                      Padding(
                        padding: const EdgeInsets.only(
                          top: 20.0,
                        ),
                        child: new Text(
                          "正在加载...",
                          style: TextStyle(fontSize: 12.0, color: Colors.white),
                        ),
                      ),
                    ],
                  )))));
    }

    return widgets;
  }

  return DefaultTabController(
      length: 2,
      child: Scaffold(
          appBar: AppBar(
            centerTitle: true,
            title: Text('作业详情'),
            actions: <Widget>[
              FlatButton(
                child: Text(
                  '作业要求',
                  style: TextStyle(color: Colors.blue),
                ),
                onPressed: () =>
                    dispatch(HomeworkDetailActionCreator.onDemand()),
              ),
            ],
            bottom: TabBar(
              isScrollable: false,
              labelColor: Colors.blue,
              indicatorColor: Colors.blue,
              indicatorPadding: EdgeInsets.symmetric(horizontal: 60),
              indicatorWeight: 3,
              tabs: [Tab(text: '学生写作详情'), Tab(text: '班级整体情况')],
            ),
          ),
          body: TabBarView(
            children: <Widget>[
              Container(
                child: Column(
                  children: <Widget>[
                    Card(
                      color: Colors.white,
                      elevation: 4.0,
                      margin: new EdgeInsets.symmetric(
                          horizontal: 8.0, vertical: 8.0),
                      child: Padding(
                          padding:
                              EdgeInsets.symmetric(horizontal: 16, vertical: 6),
                          child: Row(
                            children: <Widget>[
                              Text('学生作业',
                                  style:
                                      TextStyle(fontWeight: FontWeight.w500)),
                              Spacer(),
                              FlatButton(
                                padding: EdgeInsets.symmetric(
                                    horizontal: 16, vertical: 6),
                                color: Colors.blue,
                                textColor: Colors.white,
                                child: Text('机器一键批阅'),
                                shape: RoundedRectangleBorder(
                                    side: BorderSide(
                                      color: Colors.white,
                                      width: 0,
                                    ),
                                    borderRadius: BorderRadius.circular(2)),
                                onPressed: () {
                                  dispatch(
                                      HomeworkDetailActionCreator.onMarkAll());
                                },
                              )
                            ],
                          )),
                    ),
                    Expanded(
                      child: RefreshIndicator(
                        child: Stack(
                          children: _listView(),
                        ),
                        onRefresh: () {
                          final Completer<void> completer = Completer<void>();
                          dispatch(HomeworkDetailActionCreator.onReload(
                              () => completer.complete()));
                          return completer.future;
                        },
                      ),
                    )
                  ],
                ),
              ),
              Stack(
                children: <Widget>[
                  Positioned(
                    top: 0,
                    left: 0,
                    right: 0,
                    bottom: 0,
                    child: InAppWebView(
                      initialUrl: GlobalState.baseUrl(
                          '/correct/pub/anyone/view/homework/report.mvc?id=${state.homework.id}'),
                      initialHeaders: {'ticket': GlobalState.ticket},
                      initialOptions: {},
                      onWebViewCreated: (InAppWebViewController controller) {},
                      onLoadStart:
                          (InAppWebViewController controller, String url) {
                        print("started $url");
                      },
                      onProgressChanged:
                          (InAppWebViewController controller, int progress) {
                        print("started $progress");
                        dispatch(
                            HomeworkDetailActionCreator.progress(progress));
                      },
                      onLoadStop:
                          (InAppWebViewController controller, String url) {},
                    ),
                  ),
                  Positioned(
                      top: 0,
                      left: 0,
                      right: 0,
                      child: Offstage(
                        offstage: state.webPageProgress == 100,
                        child: SizedBox(
                          height: 2.0,
                          child: LinearProgressIndicator(
                            valueColor:
                                new AlwaysStoppedAnimation<Color>(Colors.green),
//                value: 80,
//                    backgroundColor: Colors.green,
                          ),
                        ),
                      )),
                ],
              ),
            ],
          )));
}
